const db = require("../core/mysql");
const moment = require("moment");
const md5 = require("md5");
const jwt = require("jwt-simple");

class AccountController {
    async reg(request, response, next) {
        let sql = 'INSERT INTO `userts`(`uname`,`upwd`,`uphone`,`udate`) VALUE(?,?,?,?);';
        let params = [
            request.body.name,
            md5(request.body.pwd + require("../config").key),
            request.body.phone,
            moment().format("YYYY-MM-DD HH:mm:ss")
        ]
        try {
            let reult = await db.exec(sql, params);
            if (reult && reult.affectedRows >= 1) {
                response.json({
                    code: 200,
                    msg: "注册成功~~~",

                })
            } else {
                response.json({
                    code: -200,
                    msg: "注册失败~~~",

                })
            }
        } catch (error) {
            response.json({
                code: -200,
                msg: "注册失败~~~",
                error
            })
        }
    }

    async login(request, response, next) {
        let sql = 'select * from `userts` where `uname`=? AND `upwd`=?;';
        let params = [
            request.body.name,
            md5(request.body.pwd + require("../config").key)
        ]
        try {
            let reult = await db.exec(sql, params);
            if (reult && reult.length >= 1) {
                response.json({
                    code: 200,
                    msg: "登录成功",
                    data: reult[0],
                    token: createToken(reult[0])
                })
            } else {
                response.json({
                    code: -200,
                    msg: "登录失败"
                })
            }
        } catch (error) {
            response.json({
                code: -200,
                msg: "登录失败"
            })
        }

        function createToken(data) {
            return jwt.encode({
                exp: Date.now() + (1000 * 60 * 60 * 24),
                info:data
            },require("../config").tokenKey);
        }
    }
}

module.exports=new AccountController();